package com.tzkyzj.tiremanagersystem.ui;

import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.content.ContentResolver;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.*;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.tzkyzj.tiremanagersystem.R;
import com.tzkyzj.tiremanagersystem.api.TireApiService;
import com.tzkyzj.tiremanagersystem.eneities.TireBatchRequest;
import com.tzkyzj.tiremanagersystem.eneities.TireInfo;
import com.tzkyzj.tiremanagersystem.network.ApiClient;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.*;

public class BatchAddTireActivity extends AppCompatActivity {

    // 添加角色和预填充信息的成员变量
    private String userRole;
    private String prefillVehiclePlateNumber;
    private String prefillTransportCompany;

    private static final int REQUEST_CODE_PICK_IMAGES = 1001;
    private static final int MAX_PHOTOS_PER_TIRE = 3;

    private EditText etVehiclePlateNumber, etTrailerPlateNumber, etTransportCompany, etInstallMileage, etInstallDate;
    private DatePickerDialog datePickerDialog;
    private Button btnSubmit, btnCancel;
    private ProgressBar progressBar;

    private TireApiService apiService;
    private List<TireInputView> tireInputViews = new ArrayList<>();
    private Map<Integer, List<Uri>> tirePhotosMap = new HashMap<>();
    private String selectedInstallDate;

    private int currentTireIndex = -1;
    private Map<Integer, LinearLayout> photoPreviewMap = new HashMap<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_batch_add_tire);

        // 获取用户角色和预填充信息
        getUserRoleAndPrefillData();

        initViews();
        setupRetrofit();
        setupDatePicker();
        setupTireInputs();
        setupClickListeners();

        // 根据角色设置字段状态
        setupFieldStatesByRole();
    }

    /**
     * 获取用户角色和预填充数据
     */
    private void getUserRoleAndPrefillData() {
        // 从 SharedPreferences 获取用户信息
        SharedPreferences sharedPreferences = getSharedPreferences("user_prefs", MODE_PRIVATE);
        userRole = sharedPreferences.getString("role", "DRIVER");
        prefillVehiclePlateNumber = sharedPreferences.getString("plateNumber", "");
        prefillTransportCompany = sharedPreferences.getString("company", "");

        Log.d("BatchAddTire", "用户信息 - 角色: " + userRole +
                ", 车牌: " + prefillVehiclePlateNumber +
                ", 公司: " + prefillTransportCompany);
    }

    /**
     * 根据用户角色设置字段状态
     */
    private void setupFieldStatesByRole() {
        if (userRole == null) return;

        switch (userRole) {
            case "COMPANY":
                // 运输公司角色：锁定运输公司字段
                setupTransportCompanyFields();
                break;

            case "DRIVER":
                // 司机角色：锁定车头牌号和运输公司字段
                setupDriverFields();
                break;

            default:
                // 管理员或其他角色：所有字段都可编辑
                break;
        }
    }

    /**
     * 设置运输公司角色的字段状态
     */
    private void setupTransportCompanyFields() {
        if (!TextUtils.isEmpty(prefillTransportCompany)) {
            etTransportCompany.setText(prefillTransportCompany);
            etTransportCompany.setEnabled(false);
            etTransportCompany.setFocusable(false);
            etTransportCompany.setClickable(false);
            etTransportCompany.setBackgroundColor(getResources().getColor(android.R.color.darker_gray));
            etTransportCompany.setHint("固定运输公司");

            Log.d("BatchAddTire", "运输公司角色：锁定运输公司字段为: " + prefillTransportCompany);
        }
    }

    /**
     * 设置司机角色的字段状态
     */
    private void setupDriverFields() {
        // 锁定车头牌号
        if (!TextUtils.isEmpty(prefillVehiclePlateNumber)) {
            etVehiclePlateNumber.setText(prefillVehiclePlateNumber);
            etVehiclePlateNumber.setEnabled(false);
            etVehiclePlateNumber.setFocusable(false);
            etVehiclePlateNumber.setClickable(false);
            etVehiclePlateNumber.setBackgroundColor(getResources().getColor(android.R.color.darker_gray));
            etVehiclePlateNumber.setHint("固定车头牌号");

            Log.d("BatchAddTire", "司机角色：锁定车头牌号为: " + prefillVehiclePlateNumber);
        }

        // 锁定运输公司
        if (!TextUtils.isEmpty(prefillTransportCompany)) {
            etTransportCompany.setText(prefillTransportCompany);
            etTransportCompany.setEnabled(false);
            etTransportCompany.setFocusable(false);
            etTransportCompany.setClickable(false);
            etTransportCompany.setBackgroundColor(getResources().getColor(android.R.color.darker_gray));
            etTransportCompany.setHint("固定运输公司");

            Log.d("BatchAddTire", "司机角色：锁定运输公司为: " + prefillTransportCompany);
        }
    }

    private void initViews() {
        etVehiclePlateNumber = findViewById(R.id.et_vehicle_plate_number);
        etTrailerPlateNumber = findViewById(R.id.et_trailer_plate_number);
        etTransportCompany = findViewById(R.id.et_transport_company);
        etInstallMileage = findViewById(R.id.et_install_mileage);
        etInstallDate = findViewById(R.id.et_install_date);

        btnSubmit = findViewById(R.id.btn_submit);
        btnCancel = findViewById(R.id.btn_cancel);
        progressBar = findViewById(R.id.progress_bar);

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault());
        selectedInstallDate = sdf.format(new Date());
        etInstallDate.setText(selectedInstallDate);
    }

    private void setupRetrofit() {
        // 使用统一的 ApiClient 来确保携带认证信息
        Retrofit retrofit = ApiClient.getClient();
        if (retrofit != null) {
            apiService = retrofit.create(TireApiService.class);
            Log.d("BatchAddTire", "使用 ApiClient 创建 API 服务");
        } else {
            Log.e("BatchAddTire", "ApiClient 返回的 Retrofit 为 null");
            // 如果 ApiClient 返回 null，使用原来的方式作为备选
            setupRetrofitFallback();
        }
    }

    /**
     * 备用的 Retrofit 设置方法
     */
    private void setupRetrofitFallback() {
        Log.w("BatchAddTire", "使用备用的 Retrofit 设置");
        Gson gson = new GsonBuilder()
                .setLenient()
                .create();

        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl("http://120.55.37.146:8080/")
                .addConverterFactory(GsonConverterFactory.create(gson))
                .build();
        apiService = retrofit.create(TireApiService.class);
    }

    private void setupDatePicker() {
        Calendar calendar = Calendar.getInstance();
        datePickerDialog = new DatePickerDialog(
                this,
                (view, year, month, dayOfMonth) -> {
                    selectedInstallDate = String.format(Locale.getDefault(), "%d-%02d-%02d", year, month + 1, dayOfMonth);
                    etInstallDate.setText(selectedInstallDate);
                },
                calendar.get(Calendar.YEAR),
                calendar.get(Calendar.MONTH),
                calendar.get(Calendar.DAY_OF_MONTH)
        );

        etInstallDate.setOnClickListener(v -> datePickerDialog.show());
        etInstallDate.setFocusable(false);
        etInstallDate.setClickable(true);
    }

    private void setupTireInputs() {
        LinearLayout container = findViewById(R.id.tire_inputs_container);

        String[][] axlePositions = {
                {"左外", "右外"},
                {"左外", "左内", "右内", "右外"},
                {"左外", "左内", "右内", "右外"},
                {"左外", "左内", "右内", "右外"},
                {"左外", "左内", "右内", "右外"},
                {"左外", "左内", "右内", "右外"}
        };

        for (int axle = 0; axle < axlePositions.length; axle++) {
            TextView axleTitle = new TextView(this);
            axleTitle.setText(String.format("第%d轴", axle + 1));
            axleTitle.setTextSize(16);
            axleTitle.setPadding(0, 16, 0, 8);
            axleTitle.setTextColor(getResources().getColor(android.R.color.black));
            container.addView(axleTitle);

            for (int pos = 0; pos < axlePositions[axle].length; pos++) {
                TireInputView tireInputView = new TireInputView(this, axle + 1, axlePositions[axle][pos]);
                int tireIndex = tireInputViews.size();
                tireInputView.setTireIndex(tireIndex);
                tireInputViews.add(tireInputView);
                container.addView(tireInputView);

                addPhotoPreviewArea(container, tireIndex);
            }
        }
    }

    private void addPhotoPreviewArea(LinearLayout container, int tireIndex) {
        LinearLayout previewContainer = new LinearLayout(this);
        previewContainer.setOrientation(LinearLayout.VERTICAL);
        previewContainer.setPadding(0, 8, 0, 16);

        TextView previewTitle = new TextView(this);
        previewTitle.setText("已选照片:");
        previewTitle.setTextSize(14);
        previewTitle.setTextColor(getResources().getColor(android.R.color.darker_gray));
        previewContainer.addView(previewTitle);

        HorizontalScrollView scrollView = new HorizontalScrollView(this);
        LinearLayout photoLayout = new LinearLayout(this);
        photoLayout.setOrientation(LinearLayout.HORIZONTAL);
        photoLayout.setPadding(8, 8, 8, 8);
        scrollView.addView(photoLayout);
        previewContainer.addView(scrollView);

        photoPreviewMap.put(tireIndex, photoLayout);
        container.addView(previewContainer);
    }

    private void setupClickListeners() {
        btnSubmit.setOnClickListener(v -> submitBatchTires());
        btnCancel.setOnClickListener(v -> finish());
    }

    private void submitBatchTires() {
        if (!validateInput()) {
            return;
        }

        showLoading(true);
        testServerConnection();
    }

    private void testServerConnection() {
        Log.d("NetworkDebug", "测试服务器连接...");

        // 创建一个简单的测试请求
        Call<ResponseBody> testCall = apiService.testConnection();
        testCall.enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                if (response.isSuccessful()) {
                    try {
                        String responseBody = response.body().string();
                        Log.d("NetworkDebug", "服务器连接正常，响应: " + responseBody);
                        // 服务器正常，提交实际数据
                        submitActualData();
                    } catch (IOException e) {
                        Log.e("NetworkDebug", "读取响应失败", e);
                        showLoading(false);
                        showError("服务器响应异常");
                    }
                } else {
                    // 处理认证失败的情况
                    if (response.code() == 401) {
                        showLoading(false);
                        handleUnauthorizedError();
                        return;
                    }

                    try {
                        String errorBody = response.errorBody() != null ? response.errorBody().string() : "无错误信息";
                        Log.e("NetworkDebug", "服务器返回错误: " + response.code() + ", 错误信息: " + errorBody);
                        showLoading(false);
                        showError("服务器错误: " + response.code() + "\n" + errorBody);
                    } catch (IOException e) {
                        Log.e("NetworkDebug", "读取错误响应失败", e);
                        showLoading(false);
                        showError("服务器错误: " + response.code());
                    }
                }
            }

            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {
                Log.e("NetworkDebug", "服务器连接失败", t);
                showLoading(false);
                showError("无法连接到服务器: " + t.getMessage());
            }
        });
    }

    /**
     * 处理认证失败的情况
     */
    private void handleUnauthorizedError() {
        runOnUiThread(() -> {
            Log.e("AuthError", "Session 认证失败，可能需要重新登录");
            Toast.makeText(BatchAddTireActivity.this, "登录已过期，请重新登录", Toast.LENGTH_LONG).show();

            // 清除用户数据
            SharedPreferences prefs = getSharedPreferences("user_prefs", MODE_PRIVATE);
            prefs.edit().clear().apply();

            // 清除 ApiClient 实例和 Session
            ApiClient.clearClient();

            // 跳转到登录页面
            Intent intent = new Intent(BatchAddTireActivity.this, LoginActivity.class);
            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
            startActivity(intent);
            finish();
        });
    }

    private void submitActualData() {
        TireBatchRequest batchRequest = createBatchRequest();
        if (batchRequest == null) {
            showError("请至少填写一个轮胎的信息");
            showLoading(false);
            return;
        }

        Log.d("RequestDebug", "提交数据: " + batchRequest.toString());

        try {
            // 将轮胎数据转换为 JSON
            Gson gson = new Gson();
            String tireDataJson = gson.toJson(batchRequest.getTires());

            // 构建 Multipart 请求
            MultipartBody.Part vehiclePlateNumberPart = createPartFromString("vehiclePlateNumber", batchRequest.getVehiclePlateNumber());
            MultipartBody.Part trailerPlateNumberPart = createPartFromString("trailerPlateNumber", batchRequest.getTrailerPlateNumber());
            MultipartBody.Part transportCompanyPart = createPartFromString("transportCompany", batchRequest.getTransportCompany());
            MultipartBody.Part installDatePart = createPartFromString("installDate", batchRequest.getInstallDate());
            MultipartBody.Part installMileagePart = createPartFromString("installMileage", String.valueOf(batchRequest.getInstallMileage()));
            MultipartBody.Part tireDataPart = createPartFromString("tireData", tireDataJson);

            // 构建照片 parts - 使用正确的字段名
            List<MultipartBody.Part> photoParts = createPhotoParts(batchRequest.getTires());

            // 合并所有 parts
            List<MultipartBody.Part> allParts = new ArrayList<>();
            allParts.add(vehiclePlateNumberPart);
            allParts.add(trailerPlateNumberPart);
            allParts.add(transportCompanyPart);
            allParts.add(installDatePart);
            allParts.add(installMileagePart);
            allParts.add(tireDataPart);
            allParts.addAll(photoParts);

            Log.d("RequestDebug", "发送Multipart请求，共 " + allParts.size() + " 个部分");
            Log.d("RequestDebug", "轮胎数据JSON: " + tireDataJson);

            // 使用Multipart请求
            Call<ResponseBody> call = apiService.batchAddTires(allParts);
            call.enqueue(new Callback<ResponseBody>() {
                @Override
                public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                    showLoading(false);

                    // 处理认证失败的情况
                    if (response.code() == 401) {
                        handleUnauthorizedError();
                        return;
                    }

                    try {
                        String rawResponse = "";

                        if (response.isSuccessful()) {
                            // 成功响应
                            if (response.body() != null) {
                                rawResponse = response.body().string();
                                Log.d("ResponseDebug", "成功响应: " + rawResponse);

                                // 检查响应内容，判断是否成功
                                if (rawResponse.contains("redirect:") ||
                                        rawResponse.contains("success") ||
                                        rawResponse.contains("成功")) {
                                    showSuccess("批量添加轮胎成功");
                                    new android.os.Handler().postDelayed(() -> {
                                        setResult(RESULT_OK);
                                        finish();
                                    }, 1500);
                                } else if (rawResponse.contains("error") || rawResponse.contains("失败")) {
                                    // 提取错误信息
                                    String errorMsg = extractErrorMessage(rawResponse);
                                    showError("添加失败: " + errorMsg);
                                } else {
                                    // 默认认为成功
                                    showSuccess("操作完成");
                                    new android.os.Handler().postDelayed(() -> {
                                        setResult(RESULT_OK);
                                        finish();
                                    }, 1500);
                                }
                            } else {
                                Log.e("ResponseDebug", "成功响应但响应体为空");
                                showSuccess("操作完成（无响应内容）");
                                new android.os.Handler().postDelayed(() -> {
                                    setResult(RESULT_OK);
                                    finish();
                                }, 1500);
                            }
                        } else {
                            // 错误响应
                            if (response.errorBody() != null) {
                                rawResponse = response.errorBody().string();
                                Log.e("ResponseDebug", "HTTP错误，状态码: " + response.code() + ", 错误信息: " + rawResponse);
                            } else {
                                Log.e("ResponseDebug", "HTTP错误，状态码: " + response.code() + ", 错误体为空");
                                rawResponse = "HTTP错误: " + response.code();
                            }
                            showError("服务器错误: " + response.code() + "\n" + rawResponse);
                        }
                    } catch (IOException e) {
                        Log.e("ResponseDebug", "读取响应失败", e);
                        showError("读取服务器响应失败: " + e.getMessage());
                    }
                }

                @Override
                public void onFailure(Call<ResponseBody> call, Throwable t) {
                    showLoading(false);
                    Log.e("RequestDebug", "网络请求失败", t);
                    showError("网络请求失败: " + t.getMessage());
                }
            });

        } catch (Exception e) {
            showLoading(false);
            Log.e("RequestDebug", "构建请求失败", e);
            showError("构建请求失败: " + e.getMessage());
        }
    }

    // 修复后的创建照片 parts 方法
    private List<MultipartBody.Part> createPhotoParts(List<TireInfo> tires) {
        List<MultipartBody.Part> photoParts = new ArrayList<>();

        for (int i = 0; i < tires.size(); i++) {
            List<Uri> photoUris = tirePhotosMap.get(i);
            if (photoUris != null && !photoUris.isEmpty()) {
                for (int j = 0; j < photoUris.size(); j++) {
                    try {
                        Uri photoUri = photoUris.get(j);
                        File photoFile = uriToFile(photoUri);

                        if (!photoFile.exists()) continue;

                        // 获取 MIME 类型
                        String mimeType = getMimeType(photoUri);
                        MediaType mediaType = mimeType != null ? MediaType.parse(mimeType) : MediaType.parse("image/jpeg");

                        RequestBody photoRequestBody = RequestBody.create(mediaType, photoFile);

                        // 修复字段名：使用嵌套索引格式 photos[轮胎索引][照片索引]
                        MultipartBody.Part photoPart = MultipartBody.Part.createFormData(
                                "photos[" + i + "][" + j + "]",  // 关键修复：使用嵌套索引
                                "tire_" + i + "_photo_" + j + getFileExtension(photoFile),
                                photoRequestBody
                        );
                        photoParts.add(photoPart);

                        Log.d("PhotoUpload", "添加照片: 轮胎[" + i + "] -> 照片[" + j + "], 字段名: photos[" + i + "][" + j + "], 文件名: " + photoFile.getName());

                    } catch (IOException e) {
                        Log.e("BatchAddTire", "处理照片失败: " + e.getMessage());
                    }
                }
            }
        }

        Log.d("PhotoUpload", "总共创建了 " + photoParts.size() + " 个照片部分");
        return photoParts;
    }

    // 简单的错误信息提取方法
    private String extractErrorMessage(String html) {
        // 这里可以添加更复杂的HTML解析逻辑
        if (html.contains("error")) {
            return "服务器返回错误";
        }
        return "未知错误";
    }

    private TireBatchRequest createBatchRequest() {
        TireBatchRequest request = new TireBatchRequest();

        request.setVehiclePlateNumber(etVehiclePlateNumber.getText().toString().trim());
        request.setTrailerPlateNumber(etTrailerPlateNumber.getText().toString().trim());
        request.setTransportCompany(etTransportCompany.getText().toString().trim());
        request.setInstallDate(selectedInstallDate);

        try {
            request.setInstallMileage(Integer.parseInt(etInstallMileage.getText().toString().trim()));
        } catch (NumberFormatException e) {
            request.setInstallMileage(0);
        }

        List<TireInfo> tires = new ArrayList<>();
        for (TireInputView tireInput : tireInputViews) {
            TireInfo tireInfo = tireInput.getTireInfo();
            if (tireInfo != null && !TextUtils.isEmpty(tireInfo.getTireNumber())) {
                tires.add(tireInfo);
            }
        }

        if (tires.isEmpty()) {
            return null;
        }

        request.setTires(tires);
        return request;
    }

    /**
     * 修改验证逻辑，考虑角色锁定的字段
     */
    private boolean validateInput() {
        // 对于司机角色，车头牌号已经预填充，不需要再次验证是否为空
        if (!"DRIVER".equals(userRole) && TextUtils.isEmpty(etVehiclePlateNumber.getText().toString().trim())) {
            showError("请输入车头牌号");
            return false;
        }

        // 对于运输公司和司机角色，运输公司已经预填充，不需要再次验证是否为空
        if (!"COMPANY".equals(userRole) && !"DRIVER".equals(userRole)
                && TextUtils.isEmpty(etTransportCompany.getText().toString().trim())) {
            showError("请输入运输公司");
            return false;
        }

        if (TextUtils.isEmpty(selectedInstallDate)) {
            showError("请选择装胎日期");
            return false;
        }

        if (TextUtils.isEmpty(etInstallMileage.getText().toString().trim())) {
            showError("请输入装胎公里数");
            return false;
        }

        // 检查轮胎号是否重复
        Set<String> tireNumbers = new HashSet<>();
        for (TireInputView tireInput : tireInputViews) {
            String tireNumber = tireInput.getTireNumber();
            if (!TextUtils.isEmpty(tireNumber)) {
                if (tireNumbers.contains(tireNumber)) {
                    showError("发现重复的轮胎号: " + tireNumber);
                    return false;
                }
                tireNumbers.add(tireNumber);
            }
        }

        return true;
    }

    private MultipartBody.Part createPartFromString(String name, String value) {
        if (value == null) {
            value = "";
        }
        RequestBody requestBody = RequestBody.create(MediaType.parse("text/plain"), value);
        return MultipartBody.Part.createFormData(name, null, requestBody);
    }

    // 获取文件的MIME类型
    private String getMimeType(Uri uri) {
        ContentResolver contentResolver = this.getContentResolver();
        return contentResolver.getType(uri);
    }

    // 获取文件扩展名
    private String getFileExtension(File file) {
        String name = file.getName();
        int lastDot = name.lastIndexOf('.');
        return lastDot != -1 ? name.substring(lastDot) : ".jpg";
    }

    // 或者从Uri获取扩展名
    private String getFileExtension(Uri uri) {
        String path = uri.getPath();
        if (path != null) {
            int lastDot = path.lastIndexOf('.');
            return lastDot != -1 ? path.substring(lastDot) : ".jpg";
        }
        return ".jpg";
    }

    private File uriToFile(Uri uri) throws IOException {
        InputStream inputStream = getContentResolver().openInputStream(uri);
        File file = new File(getCacheDir(), "temp_photo_" + System.currentTimeMillis() + ".jpg");
        FileOutputStream outputStream = new FileOutputStream(file);

        byte[] buffer = new byte[4096];
        int bytesRead;
        while ((bytesRead = inputStream.read(buffer)) != -1) {
            outputStream.write(buffer, 0, bytesRead);
        }

        inputStream.close();
        outputStream.close();
        return file;
    }

    private void showLoading(boolean show) {
        progressBar.setVisibility(show ? View.VISIBLE : View.GONE);
        btnSubmit.setEnabled(!show);
        btnCancel.setEnabled(!show);
    }

    private void showError(String message) {
        Toast.makeText(this, message, Toast.LENGTH_LONG).show();
    }

    private void showSuccess(String message) {
        Toast.makeText(this, message, Toast.LENGTH_LONG).show();
    }

    // 选择照片的方法 - 已修复
    public void selectPhotos(int tireIndex) {
        // 检查是否已达到最大照片数量
        List<Uri> currentPhotos = tirePhotosMap.get(tireIndex);
        if (currentPhotos != null && currentPhotos.size() >= MAX_PHOTOS_PER_TIRE) {
            showError("已达到最大照片数量 (" + MAX_PHOTOS_PER_TIRE + " 张)");
            return;
        }

        // 保存当前轮胎索引到成员变量
        this.currentTireIndex = tireIndex;

        Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
        intent.setType("image/*");
        intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
        startActivityForResult(Intent.createChooser(intent, "选择照片"), REQUEST_CODE_PICK_IMAGES);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == REQUEST_CODE_PICK_IMAGES && resultCode == RESULT_OK) {
            // 使用成员变量获取轮胎索引
            int tireIndex = this.currentTireIndex;

            if (tireIndex == -1) {
                showError("无法确定轮胎位置");
                return;
            }

            // 获取当前已选择的照片列表
            List<Uri> currentUris = tirePhotosMap.get(tireIndex);
            if (currentUris == null) {
                currentUris = new ArrayList<>();
            }

            // 计算还可以选择多少张照片
            int remainingSlots = MAX_PHOTOS_PER_TIRE - currentUris.size();
            if (remainingSlots <= 0) {
                showError("已达到最大照片数量 (" + MAX_PHOTOS_PER_TIRE + " 张)");
                this.currentTireIndex = -1;
                return;
            }

            List<Uri> selectedUris = new ArrayList<>();

            if (data != null) {
                if (data.getClipData() != null) {
                    // 多选
                    int count = Math.min(data.getClipData().getItemCount(), remainingSlots);
                    for (int i = 0; i < count; i++) {
                        selectedUris.add(data.getClipData().getItemAt(i).getUri());
                    }
                } else if (data.getData() != null) {
                    // 单选
                    selectedUris.add(data.getData());
                }
            }

            // 将新选择的照片添加到现有列表中
            currentUris.addAll(selectedUris);
            tirePhotosMap.put(tireIndex, currentUris);

            // 更新对应轮胎输入视图的照片计数
            for (TireInputView tireInput : tireInputViews) {
                if (tireInput.getTireIndex() == tireIndex) {
                    tireInput.updatePhotoCount(currentUris.size());
                    break;
                }
            }

            // 更新照片预览
            updatePhotoPreview(tireIndex, currentUris);

            // 重置当前轮胎索引
            this.currentTireIndex = -1;
        }
    }

    // 更新照片预览
    private void updatePhotoPreview(int tireIndex, List<Uri> photoUris) {
        LinearLayout previewLayout = photoPreviewMap.get(tireIndex);
        if (previewLayout == null) return;

        // 清除之前的预览
        previewLayout.removeAllViews();

        // 添加新的预览图片
        for (int i = 0; i < photoUris.size(); i++) {
            Uri photoUri = photoUris.get(i);
            ImageView imageView = createPreviewImageView(photoUri, tireIndex, i);
            previewLayout.addView(imageView);
        }
    }

    // 创建预览图片视图
    private ImageView createPreviewImageView(Uri photoUri, int tireIndex, int photoIndex) {
        ImageView imageView = new ImageView(this);

        // 设置图片尺寸
        int size = (int) (120 * getResources().getDisplayMetrics().density);
        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(size, size);
        params.setMargins(0, 0, 8, 0);
        imageView.setLayoutParams(params);

        // 设置缩放类型
        imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);

        // 加载图片
        try {
            InputStream inputStream = getContentResolver().openInputStream(photoUri);
            Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
            if (bitmap != null) {
                // 创建缩略图
                Bitmap thumbnail = Bitmap.createScaledBitmap(bitmap, size, size, true);
                imageView.setImageBitmap(thumbnail);
            }
            inputStream.close();
        } catch (IOException e) {
            Log.e("BatchAddTire", "加载预览图片失败: " + e.getMessage());
            // 设置默认图片或错误图片
            imageView.setImageResource(android.R.drawable.ic_menu_report_image);
        }

        // 添加点击事件 - 可以查看大图或删除
        imageView.setOnClickListener(v -> showPhotoOptions(tireIndex, photoIndex, photoUri));

        return imageView;
    }

    // 显示照片选项（查看或删除）
    private void showPhotoOptions(int tireIndex, int photoIndex, Uri photoUri) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("照片操作");
        builder.setItems(new String[]{"查看大图", "删除照片"}, (dialog, which) -> {
            if (which == 0) {
                // 查看大图
                showLargePhoto(photoUri);
            } else if (which == 1) {
                // 删除照片
                deletePhoto(tireIndex, photoIndex);
            }
        });
        builder.show();
    }

    // 查看大图
    private void showLargePhoto(Uri photoUri) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        ImageView imageView = new ImageView(this);

        try {
            InputStream inputStream = getContentResolver().openInputStream(photoUri);
            Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
            if (bitmap != null) {
                imageView.setImageBitmap(bitmap);
            }
            inputStream.close();
        } catch (IOException e) {
            Log.e("BatchAddTire", "加载大图失败: " + e.getMessage());
            imageView.setImageResource(android.R.drawable.ic_menu_report_image);
        }

        imageView.setAdjustViewBounds(true);
        imageView.setScaleType(ImageView.ScaleType.FIT_CENTER);

        builder.setView(imageView);
        builder.setPositiveButton("关闭", null);
        builder.show();
    }

    // 删除照片
    private void deletePhoto(int tireIndex, int photoIndex) {
        List<Uri> photoUris = tirePhotosMap.get(tireIndex);
        if (photoUris != null && photoIndex < photoUris.size()) {
            photoUris.remove(photoIndex);
            tirePhotosMap.put(tireIndex, photoUris);

            // 更新照片计数
            for (TireInputView tireInput : tireInputViews) {
                if (tireInput.getTireIndex() == tireIndex) {
                    tireInput.updatePhotoCount(photoUris.size());
                    break;
                }
            }

            // 更新预览
            updatePhotoPreview(tireIndex, photoUris);

            showSuccess("照片已删除");
        }
    }
}